<?php
set_time_limit(0);
include __DIR__.'/function.php';
require __DIR__.'/vendor/autoload.php';

use QL\QueryList;

$rang = range(1,2);


$db = new PDO('mysql:host=localhost;dbname=spider;charset=utf8','root','123456');


foreach($rang as $page){
    $url = 'https://news.ke.com/bj/baike/0033/pg'.$page.'/';

    $html = http_request($url);

    //通过 选择器  删选
    $datalist = QueryList::Query($html, [
    'img' => ['.lj-lazy','data-original','', function($item){
        //得到扩展名
        $ext = pathinfo($item,PATHINFO_EXTENSION);
        //生成文件名
        $filename = md5($item).'_'.time().'.'.$ext;
        //生成本地路径
        $filepath = __DIR__.'/public/'.$filename;

        file_put_contents($filepath, http_request($item));

        return '/public/'.$filename;
    }],
    'title' => ['.item .text .LOGCLICK', 'text'],
    'desn' => ['.item .text .summary', 'text'],
    'href' => ['.item .text > a', 'href']
    ])->data;


    // var_dump($datalist);

    //入库
    foreach($datalist as $list){
        // extract();

        $sql = "insert into spider(title,desn,pic,url) values (?,?,?,?)";
        $stmt = $db->prepare($sql);

        $stmt->execute([
            $list['title'],
            $list['desn'],
            $list['pic'],
            $list['url']
        ]);



    }

}







